using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

namespace FCalendar
{
    public class ColorPicker : System.Windows.Forms.Control
    {
        public event EventHandler ColorSelected;

        private Color _selectedColor;

        public System.Drawing.Color SelectedColor
        {
            get
            {
                return _selectedColor;
            }
            set
            {
                _selectedColor = value;
                Invalidate();
            }
        }

        protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
        {
            drawBackColor(e.Graphics);
            drawBorder(e.Graphics);
        }

        /// <summary>
        /// Draw the control border
        /// </summary>
        private void drawBorder(Graphics g)
        {
            g.DrawLines(new Pen(SystemColors.ButtonShadow),
                new Point[] {new Point(this.Width, 0), new Point(0, 0), 
                    new Point(0, this.Height)});
            g.DrawLines(new Pen(SystemColors.ButtonHighlight),
                new Point[] {new Point(this.Width - 1, 0), new Point(this.Width - 1, this.Height - 1), 
                    new Point(0, this.Height - 1)});            
        }

        /// <summary>
        /// Show the selected color as background color
        /// </summary>
        private void drawBackColor(Graphics g)
        {
            if (_selectedColor.IsEmpty)
            {
                g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;

                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                g.DrawString("N/A", new Font("Verdana", 6), new SolidBrush(SystemColors.WindowText),
                    new RectangleF(0, 0, this.Width, this.Height), sf);
            }
            else
            {
                g.FillRectangle(new SolidBrush(_selectedColor), 0, 0, this.Width, this.Height);
            }
        }

        protected override void OnMouseClick(System.Windows.Forms.MouseEventArgs e)
        {
            base.OnMouseClick(e);

            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                ColorDialog cd = new ColorDialog();
                if (cd.ShowDialog() == DialogResult.OK)
                {
                    SelectedColor = cd.Color;
                    if (ColorSelected != null)
                        ColorSelected(this, e);
                }
            }
        }
    }
}
